package racing.ui;

import java.awt.List;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import racing.client.ChatClient;
import racing.client.Message;

/**
 * The user interface for chatting.
 * 
 * @author Sarathit Sangtaweep 5510546182
 * @author Veerapat Teeravipark 5510547022
 * @version 2013
 */
public class ChatUI extends JFrame implements Observer {

	private static final long serialVersionUID = 1L;
	String name;
	ChatClient client;
	JTextField chat_text;
	JButton send_button;
	List show_list;
	ScrollPane scroll;

	/**
	 * Constructor of the class.
	 */
	public ChatUI() {
		getContentPane().setLayout(null);
		intiComponent();
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
	}

	/**
	 * Initialize the components.
	 */
	private void intiComponent() {
		
		show_list = new List();
		show_list.setLocation(17,15);
		show_list.setSize(350,200);
		getContentPane().add(show_list);

		chat_text = new JTextField();
		chat_text.setLocation(17,233);
		chat_text.setSize(225,30);
		chat_text.setText("");
		chat_text.setColumns(10);
		getContentPane().add(chat_text);

		send_button = new JButton();
		send_button.setLocation(267,233);
		send_button.setSize(100,30);
		send_button.setText("send");
		send_button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (chat_text.getText().trim().equals("")) {
					JOptionPane.showMessageDialog(null, "Please input message.",
							"Announce", JOptionPane.WARNING_MESSAGE);
				}
				else { 
					try {
						client.sendToServer(new Message(name,chat_text.getText()));
					} catch (IOException e) {
						e.printStackTrace();
					}
					chat_text.setText("");
					chat_text.requestFocus();
				}
			}
		});
		getContentPane().add(send_button);
		getRootPane().setDefaultButton(send_button);

		setTitle("Chatbox");
		setSize(400,325);
		setResizable(false);
	}

	/**
	 * Run the user interface.
	 */
	public void run() {
		pack();
		setVisible(true);
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		if (arg1 instanceof Message) {
			Message message = (Message) arg1;
			String name = message.getCommand();
			String messageText = message.getMessage();
			show_list.add(name+" : "+messageText);
			show_list.select(show_list.getItemCount()-1);
		}
	}

	/**
	 * Set client.
	 * @param chatClient client to be set.
	 */
	public void setClient(ChatClient chatClient) {
		this.client = chatClient;
		client.addObserver(this);
	}

	/**
	 * Set the name.
	 * @param name the name to be set.
	 */
	public void setName(String name) {
		this.name = name;
	}
}
